package com.heima.article.controller;

import com.heima.article.entity.ApArticle;
import com.heima.article.es.ApArticleSearch;
import com.heima.article.es.IApArticleRepository;
import com.heima.article.service.IApArticleService;
import com.heima.common.dto.ResponseResult;
import io.swagger.annotations.Api;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author WSJ
 * @Date 2022-03-26-16:36
 * @Version 1.0 （版本号）
 */
@RestController
@RequestMapping("/test")
@Api(tags = "分布式es索引创建")
public class TestController {

    @Autowired
    private IApArticleService articleService;

    @Autowired
    private ElasticsearchRestTemplate restTemplate;

    @Autowired
    private IApArticleRepository repository;


    @GetMapping("/es/index")
    public ResponseResult index() {
        restTemplate.createIndex(ApArticleSearch.class);
        return ResponseResult.okResult();
    }

    @GetMapping("/es/mapping")
    public ResponseResult map() {
        restTemplate.putMapping(ApArticleSearch.class);
        return ResponseResult.okResult();
    }

    @GetMapping("/es/add")
    public ResponseResult add() {
        List<ApArticle> list = articleService.list();
        List<IndexQuery> queries = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            for (ApArticle apArticle : list) {
                ApArticleSearch search = new ApArticleSearch();
                BeanUtils.copyProperties(apArticle,search);
                IndexQuery query = new IndexQuery();
                query.setId(search.getId().toString());
                query.setObject(search);
                queries.add(query);
            }
        }
        restTemplate.bulkIndex(queries);
        return ResponseResult.okResult();
    }

    @GetMapping("/es/re")
    public ResponseResult re() {
        //先删除所有
        repository.deleteAll();
        //添加
        List<ApArticle> list = articleService.list();
        List<ApArticleSearch> listS = new ArrayList<>();
        for (ApArticle apArticle : list) {
            ApArticleSearch search = new ApArticleSearch();
            BeanUtils.copyProperties(apArticle, search);
            listS.add(search);
        }
        repository.saveAll(listS);
        return ResponseResult.okResult();
    }
}
